package Sort.sort2020;

/**
 * 归并排序
 *
 * @author leiwenkang
 * @date 2020/3/29
 */
public class MergeSort {
    public static void main(String[] args) {
        int[] array = {3, 8, 4, 6, 7, 2, 5, 9, 1};
        mergeSort(array);
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]);
            System.out.print(" ");
        }
    }

    public static void mergeSort(int[] array) {
        if (array == null || array.length == 0) {
            return;
        }

        mergeSort(array, 0, array.length - 1);
    }

    private static void mergeSort(int[] array, int start, int end) {
        if (start >= end) {
            return;
        }
        int mid = (start + end) >> 1;
        //左边排序
        mergeSort(array, start, mid);
        //右边排序
        mergeSort(array, mid + 1, end);
        //合并两个排序列表
        mergeSort(array, start, mid, end);
    }

    private static void mergeSort(int[] array, int start, int mid, int end) {
        int first = start;
        int second = mid + 1;
        int third = 0;

        //新数组
        int[] thirdArr = new int[end - start + 1];
        while (first <= mid && second <= end) {
            if (array[first] <= array[second]) {
                thirdArr[third++] = array[first++];
            } else {
                thirdArr[third++] = array[second++];
            }
        }

        while (first <= mid) {
            thirdArr[third++] = array[first++];
        }

        while (second <= end) {
            thirdArr[third++] = array[second++];
        }

        //新数组覆盖老数组
        int i = 0;
        while (start <= end) {
            array[start++] = thirdArr[i++];
        }
    }
}
